<template>
  <div>
    <el-form ref="login" :model="user" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="user.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input type="password" v-model="user.pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { userLogin } from '_api'
export default {
  name: 'loginPage',
  data () {
    return {
      user: {
        userName: '',
        pwd: ''
      },
      rules: {
        userName: [
          {
            required: true,
            message: '用户名必填'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码必填'
          }
        ]
      }
    }
  },
  methods: {
    onSubmit () {
      this.$refs.login.validate(valid => {
        if (valid) {
          userLogin(this.user).then(res => {
            if (res.data.code === 200) {
              // 缓存中备份 防止vuex数据丢失
              const { userInfo, token, role } = res.data.data
              localStorage.setItem('userInfo', JSON.stringify(userInfo))
              localStorage.setItem('token', token)
              localStorage.setItem('role', role)
              // 存储vuex中
              this.$store.commit('user/INIT_USER', res.data.data)
              this.$message({
                type: 'success',
                message: res.data.msg,
                duration: 1500,
                onClose: () => {
                  this.$router.replace('/dashBoard')
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
